package com.cinc.ebc.mm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cinc.ebc.mm.entity.MmPurchaseOrder;
import com.cinc.ebc.mm.entity.MmPurchaseOrderDetail;
import com.cinc.ebc.mm.model.*;
import com.cinc.ebc.mm.service.IMmPurchaseOrderDetailService;
import com.cinc.ebc.mm.service.IMmPurchaseOrderService;
import com.cinc.ebc.mm.vo.MmPurchaseOrderDetailPage;
import com.cinc.ebc.mm.vo.MmPurchaseOrderPage;
import com.cinc.ebc.mm.vo.MmRptPurOrderStatPage;
import com.cinc.ebc.quote.project.entity.QuoteProject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 采购订单
 * @Author: jeecg-boot
 * @Date:   2022-03-20
 * @Version: V1.0
 */
@Api(tags="采购订单")
@RestController
@RequestMapping("/mm/purchaseOrder")
@Slf4j
public class MmPurchaseOrderController {
	@Autowired
	private IMmPurchaseOrderService mmPurchaseOrderService;
	@Autowired
	private IMmPurchaseOrderDetailService mmPurchaseOrderDetailService;

	/**
	 * 分页列表查询
	 *
	 * @param mmPurchaseOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采购订单-分页列表查询")
	@ApiOperation(value="采购订单-分页列表查询", notes="采购订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MmPurchaseOrder mmPurchaseOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MmPurchaseOrder> queryWrapper = QueryGenerator.initQueryWrapper(mmPurchaseOrder, req.getParameterMap());
		Page<MmPurchaseOrder> page = new Page<>(pageNo, pageSize);
		IPage<MmPurchaseOrder> pageList = mmPurchaseOrderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 订单明细分页列表查询
	  *
	  * @param mmPurchaseOrderDetailPage
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @PermissionData(pageComponent = "ebc/mm/MmPurchaseOrderDetailList")
	 @AutoLog(value = "采购订单明细-分页列表查询")
	 @ApiOperation(value="采购订单明细-分页列表查询", notes="采购订单明细-分页列表查询")
	 @GetMapping(value = "/detailPageList")
	 public Result<?> queryDetailPageList(MmPurchaseOrderDetailPage mmPurchaseOrderDetailPage,
										  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
										  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
										  HttpServletRequest req) {
		 Page<MmPurchaseOrderDetailModel> page = new Page<>(pageNo, pageSize);
		 IPage<MmPurchaseOrderDetailModel> pageList = mmPurchaseOrderService.detailPage(page, mmPurchaseOrderDetailPage);
		 return Result.OK(pageList);
	 }

	 /**
	  * 订单明细分页列表查询
	  *
	  * @param mmPurchaseOrderDetailPage
	  * @return
	  */
	 @PermissionData(pageComponent = "ebc/mm/MmPurchaseOrderDetailList")
	 @AutoLog(value = "采购订单明细-分页列表查询")
	 @ApiOperation(value="采购订单明细-分页列表查询", notes="采购订单明细-分页列表查询")
	 @GetMapping(value = "/detailList")
	 public Result<?> queryDetailList(MmPurchaseOrderDetailPage mmPurchaseOrderDetailPage) {
		 List<MmPurchaseOrderDetailModel> list = mmPurchaseOrderService.detailList( mmPurchaseOrderDetailPage);
		 return Result.OK(list);
	 }

	 /**
	  * 采购明细-最新采购价查询
	  *
	  * @param materialIdS
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "采购明细-最新采购价查询")
	 @ApiOperation(value="采购明细-最新采购价查询", notes="采购明细-最新采购价查询")
	 @GetMapping(value = "/queryLatestPrice")
	 public Result<?> queryLatestPrice(@RequestParam(name="materialIds") String materialIds, @RequestParam(name="supplyId", required = false) String supplyId) {

		 Map<String, BigDecimal> materialIdAndPrice= mmPurchaseOrderService.queryLatestPrice(materialIds, supplyId);

		 return Result.OK(materialIdAndPrice);
	 }

	 @AutoLog(value = "采购订单-供应商物料统计查询")
	 @ApiOperation(value="采购订单-供应商物料统计查询", notes="采购订单-供应商物料统计查询")
	 @GetMapping(value = "/supplyMaterialStatList")
	 public Result<?> querySupplyMaterialStatPageList(MmPurchaseOrderDetailPage detailPage,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 Page<MmPurchaseOrderSupplyMaterialModel> page = new Page<>(pageNo, pageSize);
		 mmPurchaseOrderService.querySupplyMaterialStatPageList(page, detailPage);
		 return Result.OK(page);
	 }

	/**
	 *   添加
	 *
	 * @param mmPurchaseOrderPage
	 * @return
	 */
	@AutoLog(value = "采购订单-添加")
	@ApiOperation(value="采购订单-添加", notes="采购订单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody MmPurchaseOrderPage mmPurchaseOrderPage) {
		MmPurchaseOrder mmPurchaseOrder = new MmPurchaseOrder();
		BeanUtils.copyProperties(mmPurchaseOrderPage, mmPurchaseOrder);
		mmPurchaseOrderService.saveMain(mmPurchaseOrder, mmPurchaseOrderPage.getMmPurchaseOrderDetailList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mmPurchaseOrderPage
	 * @return
	 */
	@AutoLog(value = "采购订单-编辑")
	@ApiOperation(value="采购订单-编辑", notes="采购订单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody MmPurchaseOrderPage mmPurchaseOrderPage) throws Exception {
		MmPurchaseOrder mmPurchaseOrder = new MmPurchaseOrder();
		BeanUtils.copyProperties(mmPurchaseOrderPage, mmPurchaseOrder);
		MmPurchaseOrder mmPurchaseOrderEntity = mmPurchaseOrderService.getById(mmPurchaseOrder.getId());
		if(mmPurchaseOrderEntity==null) {
			return Result.error("未找到对应数据");
		}
		mmPurchaseOrderService.updateMain(mmPurchaseOrder, mmPurchaseOrderPage.getMmPurchaseOrderDetailList());
		return Result.OK("编辑成功!");
	}

	 /**
	  *  编辑
	  *
	  * @param mmPurchaseOrder
	  * @return
	  */
	 @AutoLog(value = "采购订单-编辑")
	 @ApiOperation(value="采购订单-编辑", notes="采购订单-编辑")
	 @PutMapping(value = "/modifyPurchaseOrder")
	 public Result<?> modifyPurchaseOrder(@RequestBody MmPurchaseOrder mmPurchaseOrder) throws Exception {
		 MmPurchaseOrder mmPurchaseOrderEntity = mmPurchaseOrderService.getById(mmPurchaseOrder.getId());
		 if(mmPurchaseOrderEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 mmPurchaseOrderService.updateById(mmPurchaseOrder);
		 return Result.OK("编辑成功!");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购订单-通过id删除")
	@ApiOperation(value="采购订单-通过id删除", notes="采购订单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		mmPurchaseOrderService.delMain(id);
		return Result.OK("删除成功!");
	}
	 /**
	  *   通过id逻辑删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "采购订单-通过id删除")
	 @ApiOperation(value="采购订单-通过id删除", notes="采购订单-通过id删除")
	 @DeleteMapping(value = "/deleteLogic")
	 public Result<?> deleteLogic(@RequestParam(name="id",required=true) String id) throws RuntimeException {
		 mmPurchaseOrderService.delLogicMain(id);
		 return Result.OK("删除成功!");
	 }


	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采购订单-批量删除")
	@ApiOperation(value="采购订单-批量删除", notes="采购订单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mmPurchaseOrderService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	 /**
	  *   通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "采购订单明细-通过id删除")
	 @ApiOperation(value="采购订单明细-通过id删除", notes="采购订单明细-通过id删除")
	 @DeleteMapping(value = "/deleteDetail")
	 public Result<?> deleteDetail(@RequestParam(name="id",required=true) String id) throws Exception {
		 mmPurchaseOrderService.delDetail(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  *  批量删除明细
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "采购订单明细-批量删除")
	 @ApiOperation(value="采购订单明细-批量删除", notes="采购订单明细-批量删除")
	 @DeleteMapping(value = "/deleteBatchDetail")
	 public Result<?> deleteBatchDetail(@RequestParam(name="ids",required=true) String ids) throws Exception {
		 this.mmPurchaseOrderService.delBatchDetail(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功！");
	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购订单-通过id查询")
	@ApiOperation(value="采购订单-通过id查询", notes="采购订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		MmPurchaseOrder mmPurchaseOrder = mmPurchaseOrderService.getById(id);
		if(mmPurchaseOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mmPurchaseOrder);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购订单明细通过主表ID查询")
	@ApiOperation(value="采购订单明细主表ID查询", notes="采购订单明细-通主表ID查询")
	@GetMapping(value = "/queryDetailListByMainId")
	public Result<?> queryDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<MmPurchaseOrderDetailModel> mmPurchaseOrderDetailList = mmPurchaseOrderDetailService.selectByMainId(id);
		return Result.OK(mmPurchaseOrderDetailList);
	}

	 /**
	  * 通过id分页查询
	  *
	  * @param mainId
	  * @return
	  */
	 @AutoLog(value = "采购订单明细通过主表ID查询")
	 @ApiOperation(value="采购订单明细主表ID查询", notes="采购订单明细-通主表ID查询")
	 @GetMapping(value = "/queryDetailPageListByMainId")
	 public Result<?> queryDetailPageListByMainId(@RequestParam(name="mainId",required=true) String mainId,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 Page<MmPurchaseOrderDetailModel> page = new Page<>(pageNo, pageSize);
		 mmPurchaseOrderDetailService.selectPageByMainId(page, mainId);
		 return Result.OK(page);
	 }

	 /**
	  * 首页采购订单列表查询
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "项目-首页采购订单列表查询")
	 @ApiOperation(value = "项目-首页采购订单列表查询", notes = "项目-首页采购订单列表查询")
	 @GetMapping(value = "/queryListFp")
	 public Result<?> queryListFp(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
								  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 QueryWrapper<MmPurchaseOrder> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("id", "order_no", "supply_id", "project_id","order_date", "total_price","buyer","status");
		 Page<MmPurchaseOrder> page = new Page<>(pageNo, pageSize);
		 IPage<MmPurchaseOrder> pageList = mmPurchaseOrderService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param mmPurchaseOrder
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MmPurchaseOrder mmPurchaseOrder) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<MmPurchaseOrder> queryWrapper = QueryGenerator.initQueryWrapper(mmPurchaseOrder, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<MmPurchaseOrder> queryList = mmPurchaseOrderService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<MmPurchaseOrder> mmPurchaseOrderList = new ArrayList<MmPurchaseOrder>();
      if(oConvertUtils.isEmpty(selections)) {
          mmPurchaseOrderList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          mmPurchaseOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<MmPurchaseOrderPage> pageList = new ArrayList<MmPurchaseOrderPage>();
      for (MmPurchaseOrder main : mmPurchaseOrderList) {
          MmPurchaseOrderPage vo = new MmPurchaseOrderPage();
          BeanUtils.copyProperties(main, vo);
          List<MmPurchaseOrderDetailModel> mmPurchaseOrderDetailList = mmPurchaseOrderDetailService.selectByMainId(main.getId());
          List<MmPurchaseOrderDetail> detailList = new ArrayList<>();
          for(MmPurchaseOrderDetailModel detailModel : mmPurchaseOrderDetailList){
			  MmPurchaseOrderDetail orderDetail = new MmPurchaseOrderDetail();
			  BeanUtils.copyProperties(detailModel, orderDetail);
			  detailList.add(orderDetail);
		  }
          vo.setMmPurchaseOrderDetailList(detailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "采购订单列表");
      mv.addObject(NormalExcelConstants.CLASS, MmPurchaseOrderPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采购订单数据", "导出人:"+sysUser.getRealname(), "采购订单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<MmPurchaseOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), MmPurchaseOrderPage.class, params);
              for (MmPurchaseOrderPage page : list) {
                  MmPurchaseOrder po = new MmPurchaseOrder();
                  BeanUtils.copyProperties(page, po);
                  mmPurchaseOrderService.saveMain(po, page.getMmPurchaseOrderDetailList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 采购统计查询-物料
	  *
	  * @param mmRptPurOrderStatPage
	  * @return
	  */
	 @AutoLog(value = "采购统计查询-物料")
	 @ApiOperation(value="采购统计查询-物料", notes="采购统计查询-物料")
	 @GetMapping(value = "/rptMaterialStatList")
	 public Result<?> queryRptMaterialStatList(MmRptPurOrderStatPage mmRptPurOrderStatPage,
									   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 Page<MmRptPurOrderMaterialStatModel> page = new Page<>(pageNo, pageSize);
		 IPage<MmRptPurOrderMaterialStatModel> list = mmPurchaseOrderService.queryRptMaterialStatList(page,mmRptPurOrderStatPage);
		 return Result.OK(list);
	 }

	 /**
	  * 采购统计查询-物料-列合计
	  *
	  * @param mmRptPurOrderStatPage
	  * @return
	  */
	 @AutoLog(value = "采购统计查询-物料-列合计")
	 @ApiOperation(value="采购统计查询-物料-列合计", notes="采购统计查询-物料-列合计")
	 @GetMapping(value = "/rptMaterialStatTotal")
	 public Result<?> queryRptMaterialStatTotal(MmRptPurOrderStatPage mmRptPurOrderStatPage) {

		 MmRptPurOrderMaterialStatTotalModel data = mmPurchaseOrderService.queryRptMaterialStatTotal(mmRptPurOrderStatPage);
		 return Result.OK(data);
	 }

	 /**
	  * 采购统计查询-供应商
	  *
	  * @param mmRptPurOrderStatPage
	  * @return
	  */
	 @AutoLog(value = "采购统计查询-供应商")
	 @ApiOperation(value="采购统计查询-供应商", notes="采购统计查询-供应商")
	 @GetMapping(value = "/rptSupplyStatList")
	 public Result<?> queryRptSupplyStatList(MmRptPurOrderStatPage mmRptPurOrderStatPage,
											   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
											   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 Page<MmRptPurOrderSupplyStatModel> page = new Page<>(pageNo, pageSize);
		 IPage<MmRptPurOrderSupplyStatModel> list = mmPurchaseOrderService.queryRptSupplyStatList(page,mmRptPurOrderStatPage);
		 return Result.OK(list);
	 }

	 /**
	  * 采购统计查询-供应商-列合计
	  *
	  * @param mmRptPurOrderStatPage
	  * @return
	  */
	 @AutoLog(value = "采购统计查询-供应商-列合计")
	 @ApiOperation(value="采购统计查询-供应商-列合计", notes="采购统计查询-供应商-列合计")
	 @GetMapping(value = "/rptSupplyStatTotal")
	 public Result<?> queryRptSupplyStatTotal(MmRptPurOrderStatPage mmRptPurOrderStatPage) {

		 MmRptPurOrderSupplyStatTotalModel data = mmPurchaseOrderService.queryRptSupplyStatTotal(mmRptPurOrderStatPage);
		 return Result.OK(data);
	 }

	 /**
	  * 采购统计查询-采购员
	  *
	  * @param mmRptPurOrderStatPage
	  * @return
	  */
	 @AutoLog(value = "采购统计查询-采购员")
	 @ApiOperation(value="采购统计查询-采购员", notes="采购统计查询-采购员")
	 @GetMapping(value = "/rptBuyerStatList")
	 public Result<?> queryRptBuyerStatList(MmRptPurOrderStatPage mmRptPurOrderStatPage,
											 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
											 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 Page<MmRptPurOrderBuyerStatModel> page = new Page<>(pageNo, pageSize);
		 IPage<MmRptPurOrderBuyerStatModel> list = mmPurchaseOrderService.queryRptBuyerStatList(page,mmRptPurOrderStatPage);
		 return Result.OK(list);
	 }

	 /**
	  * 采购统计查询-采购员-列合计
	  *
	  * @param mmRptPurOrderStatPage
	  * @return
	  */
	 @AutoLog(value = "采购统计查询-采购员-列合计")
	 @ApiOperation(value="采购统计查询-采购员-列合计", notes="采购统计查询-采购员-列合计")
	 @GetMapping(value = "/rptBuyerStatTotal")
	 public Result<?> queryRptBuyerStatTotal(MmRptPurOrderStatPage mmRptPurOrderStatPage) {

		 MmRptPurOrderBuyerStatTotalModel data = mmPurchaseOrderService.queryRptBuyerStatTotal(mmRptPurOrderStatPage);
		 return Result.OK(data);
	 }
}
